package io.gitee.hejiang.jersey;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;

import org.springframework.util.StreamUtils;

/**
 * 支持前端界面修改 swagger yaml 配置文件
 */
@Path("/swagger")
public class SwaggerYamlProvider {
	@Context
	JerseyResourceConfig config;

	static Charset utf8 = Charset.forName("utf-8");

	@GET
	@Produces("application/json;charset=utf-8")
	public Object download() {
		Map<String, String> ret = new HashMap<>();
		try (InputStream in = new FileInputStream(
				((JerseyResourceConfig) config).getInflectorConfiguration()
						.getSwaggerUrl());) {
			ret.put("config", StreamUtils.copyToString(in, utf8));
		} catch (IOException e) {
			throw new WebApplicationException(e.getMessage());
		}

		return ret;
	}

	@GET
	@Path("/json")
	@Produces("application/json;charset=utf-8")
	public Object getSwaggerJson() {
		Object obj = null;
		try (InputStream in = new FileInputStream(
				((JerseyResourceConfig) config).getInflectorConfiguration()
						.getSwaggerUrl());) {
			obj = new org.yaml.snakeyaml.Yaml().load(in);
		} catch (IOException e) {
			throw new WebApplicationException(e.getMessage());
		}

		return obj;
	}
	

	@PUT
	@Consumes("application/json;charset=utf-8")
	public Response upload(Map<String, String> body) {
		try (OutputStream out = new FileOutputStream(
				((JerseyResourceConfig) config).getInflectorConfiguration()
						.getSwaggerUrl());) {
			StreamUtils.copy(body.get("config"), utf8, out);
		} catch (IOException e) {
			throw new WebApplicationException(e.getMessage());
		}

		return Response.ok().entity("OK").build();
	}
}
